<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="100px">
        <el-form-item label="工厂">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            clearable
            @change="selectPlant(searchParam.plantId)"
            filterable
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            clearable
            filterable
          >
            <el-option
              v-for="item in workShopList"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="工艺路线编号">
          <el-input
            v-model="searchParam.routingCode"
            placeholder="请输入工艺路线编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item label="工艺路线名称">
          <el-input
            v-model="searchParam.routingName"
            placeholder="请输入工艺路线名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <div v-if="isExpanded" style="display: inline">
          <el-form-item label="工艺路线分组">
            <el-select
              v-model="searchParam.routingGroupId"
              clearable
              placeholder="请选择工艺路线分组"
              filterable
            >
              <el-option
                v-for="item in routeGroups"
                :key="item.id"
                :label="item.routingGroupName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="制造环节角色">
            <el-select
              v-model="searchParam.manufacturingRole"
              placeholder="请选择制造环节角色"
              clearable
            >
              <el-option
                v-for="item in useDictionary('ManufacturingRole')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="工艺路线状态">
            <el-select
              v-model="searchParam.routingState"
              placeholder="请选择工艺路线状态"
              clearable
            >
              <el-option
                v-for="item in useDictionary('RoutingState')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="版本编号">
            <el-input
              v-model="searchParam.versionNo"
              placeholder="请输入版本编号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="restone"><i-ep-refresh />重置</el-button>
          <el-button type="primary" @click="toggleSearchArea" link>
            {{ isExpanded ? "收起" : "展开" }}
            <el-icon v-if="isExpanded" class="el-icon--right">
              <i-ep-arrowUp color="#409EFC" />
            </el-icon>
            <el-icon v-else class="el-icon--right">
              <i-ep-arrowDown color="#409EFC" />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          :loading="stopLoading"
          @click="stopParam()"
        >
          <i-ep-delete />
          批量停用
        </el-button>
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed />
        <el-table-column
          label="工艺路线编号"
          prop="routingCode"
          min-width="120"
          show-overflow-tooltip
          align="center"
          fixed
        />

        <el-table-column
          label="工艺路线名称"
          prop="routingName"
          min-width="200"
          show-overflow-tooltip
          align="center"
          fixed
        />
        <el-table-column
          label="版本编号"
          prop="versionNo"
          min-width="100"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="工艺路线分组"
          prop="routingGroupName"
          min-width="150"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="生产节拍(秒)"
          prop="tactTime"
          min-width="110"
          header-align="center"
          align="right"
          show-overflow-tooltip
        />
        <el-table-column
          label="整体加工时长"
          prop="totalTime"
          min-width="110"
          header-align="center"
          align="right"
          show-overflow-tooltip
        />
        <el-table-column
          label="制造环节角色"
          prop="manufacturingRole"
          min-width="110"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{
              useDictionary(
                "ManufacturingRole",
                scope.row.manufacturingRole ?? ""
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="需要人数"
          prop="memberUse"
          header-align="center"
          align="right"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="路线状态"
          prop="routingState"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("RoutingState", scope.row.routingState ?? "") }}
          </template>
        </el-table-column>
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="工作中心"
          prop="workCenterCode"
          min-width="120"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-show="scope.row.workCenterCode">
              {{ `${scope.row.workCenterCode}-${scope.row.workCenterName}` }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="是否启用"
          align="center"
          prop="enabled"
          min-width="100"
        >
          <template #default="scope">
            <el-tag v-show="scope.row.enabled === 1" type="success">是</el-tag>
            <el-tag v-show="scope.row.enabled !== 1" type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          align="center"
          show-overflow-tooltip
        />

        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <!-- <el-button
              type="primary"
              size="small"
              link
              :loading="copyLoading"
              @click="openDialogs(scope.row, true)"
            >
              复制
            </el-button> -->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row, true)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row, false)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              link
              @click="jumpUrl(scope.row)"
            >
              工序
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="deleteData(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <add-mes-routing
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :plantList="plantList"
      :routeGroups="routeGroups"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readonly"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import usePlant from "@/utils/usePlant";
import {
  getPlantList,
  getWorkShopList,
  getMesRouteGroupList,
} from "@/utils/commonData";
import request from "@/utils/request";
import router from "@/router";

defineOptions({
  name: "MESMESROUTINGLIST",
  inheritAttrs: false,
});
const { userPlantInfo } = usePlant();

// 请求参数
const requestApi = "/mes/mesrouting/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 工厂编号列表
const plantList: any = ref([]);

// 工作中心列表
const workShopList: any = ref([]);

async function selectPlant(id: string) {
  workShopList.value = (await getWorkShopList(id)) ?? [];
  searchParam.value = { ...searchParam.value, workCenterId: "" };
}

// 初始化搜索参数数据
const searchParamInit = {
  plantId: userPlantInfo.value?.id,
  workCenterId: "",
  routingCode: "",
  routingName: "",
  routingGroupId: "",
  manufacturingRole: "",
  routingState: "",
  versionNo: "",
};

const deleteParam = {
  api: "/mes/mesrouting/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}
const isExpanded = ref(false);
const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

function jumpUrl(row: any) {
  router.push({
    path: "/mes/mesRouting/progress",
    query: {
      id: row.id,
    },
  });
}

// 切换搜索折叠
function toggleSearchArea() {
  isExpanded.value = !isExpanded.value;
}

// 删除/mesrouting/delete
const deleteData = async (id: string) => {
  ElMessageBox.confirm("确定删除该条生产线么吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mes/mesrouting/delete",
        method: "post",
        data: { id },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getTableList();
      }
    })
    .catch(() => {});
};

// 批量停用接口
const stopLoading = ref(false);
const stopParam = async () => {
  ElMessageBox.confirm("确定批量停用吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      stopLoading.value = true;
      const res: any = await request({
        url: "/mes/mesrouting/batchStopUsing",
        method: "post",
        data: { ids: ids.value },
      }).finally(() => {
        stopLoading.value = false;
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量停用成功",
        });
      }
      getTableList();
    })
    .catch(() => {});
};

// 工艺路线分组
const routeGroups: any = ref([]);

const addDialog = reactive<DialogOption>({
  visible: false,
  readonly: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  const { data } = await request({
    url: `/mes/mesrouting/get/${id}`,
    method: "get",
  });
  addDialog.data = data;
}

// 查询详情
async function copy(id: string) {
  const { data } = await request({
    url: `/mes/mesrouting/copy/${id}`,
    method: "get",
  });
}
/** 打开生产订单表单弹窗 详情 */
function openDialog(roleObj?: any, isReadonly?: boolean) {
  if (roleObj) {
    addDialog.readonly = isReadonly;
    addDialog.title = isReadonly ? "查看" : "编辑";
    getInfo(roleObj.id);
  } else {
    addDialog.readonly = false;
    addDialog.title = "新增";
    addDialog.data = {};
  }
  addDialog.visible = true;
}
const copyLoading = ref(false);
/** 打开生产订单表单弹窗 详情 */
function openDialogs(roleObj?: any, isReadonly?: boolean) {
  ElMessageBox.confirm("确定复制吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      copyLoading.value = true;
      const res: any = await request({
        url: `/mes/mesrouting/copy/${roleObj.id}`,
        method: "get",
      }).finally(() => {
        copyLoading.value = false;
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "复制成功",
        });
      }
      getTableList();
    })
    .catch(() => {});
}
/** 打开生产订单表单弹窗 详情 */

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function restone(value: boolean) {
  reset();
  plantList.value = (await getPlantList()) || [];
  searchParam.value.plantId = plantList.value[0].id;
  selectPlant(searchParam.plantId);
}
// 页面初始化
onMounted(async () => {
  selectPlant(userPlantInfo.value?.id);
  getTableList();
  plantList.value = (await getPlantList()) || [];
  searchParam.value.plantId = plantList.value[0].id;
  selectPlant(searchParam.plantId);
  routeGroups.value = (await getMesRouteGroupList()) || [];
});
</script>
